function Game (el){

    //保存地图对象
    this.el = document.querySelector(el)
    //创建地图
    this.map = new Map(this.el)
    this.map.create()
    //创建食物
    this.food = new Food(this.el)
    this.food.create()
    //创建蛇
    this.snake = new Snake(this.el)
    this.snake.create()

    this.t= null

}

Game.prototype.start = function (){
        this.t=setInterval(() => {
        this.snake.move()
        if(this.snake.SnakeObj[0].x<0 ||this.snake.SnakeObj[0].x>39 ||this.snake.SnakeObj[0].y<0||this.snake.SnakeObj[0].y>19){
            clearInterval(this.t)
            alert('game over')
            this.snake.remove()
            this.snake.SnakeObj =[
                { x: 3, y :2, color:'red', el:null},  //蛇头
                { x: 2, y :2, color:'blue', el:null}, // 蛇身
                { x: 1, y :2, color:'blue', el:null}  // 蛇的身体
            ]
        }

        let SnakeX = this.snake.SnakeObj[0].x*20
        let SnakeY = this.snake.SnakeObj[0].y*20
        let FoodX = this.food.foodx
        let FoodY = this.food.foody
        if(SnakeX==FoodX&&SnakeY==FoodY){

            let last = this.snake.SnakeObj[this.snake.SnakeObj.length-1]

            this.snake.SnakeObj.push({
                x: last.x, 
                y :last.y,
                color:last.color, 
                el:null
            })
            this.snake.create()
            this.food.move()
        }
    },100)
    

    //监控键盘改变蛇的direction
document.addEventListener('keydown',(evt) =>{
    e=evt || window.event
    
    //获取键盘
    console.log(e.keyCode)

    switch(e.keyCode){
        case 38:
        if(this.snake.direction =='buttom'){
            alert('game over')
            clearInterval(this.t)
        }
        this.snake.direction = 'top'
        break;
        case 40:
        if(this.snake.direction =='top'){
            alert('game over')
            clearInterval(this.t)
        }
        this.snake.direction = 'buttom'
        break;
        case 37:
        if (this.snake.direction == 'right') {
             alert('game over')
             clearInterval(this.t)
        }
        this.snake.direction = 'left'
        break;
        case 39:
        if (this.snake.direction == 'left') {
            alert('game over')
            clearInterval(this.t)
        }
        this.snake.direction = 'right'
        break;
        default:
        break;
        }
    })  
}

